﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace GogTasks.Logic
{
    public class TextBoxTraceListener : TraceListener
    {
        private TextBox _textBox;
        public TextBoxTraceListener(TextBox textBox)
        {
            _textBox = textBox;
        }

        public override void Write(string message)
        {
            Write(message, String.Empty);
        }

        public override void WriteLine(string message)
        {
            Write(message, Environment.NewLine);
        }

        private delegate void WriteHandler(string message, string newLineOrBlank);
        private new void Write(string message, string newLineOrBlank)
        {
            if (Thread.CurrentThread.IsBackground)
            {
                _textBox.Invoke(new WriteHandler(Write), new object[] { message, newLineOrBlank });
            }
            else
            {
                try
                {
                    _textBox.Text += message + newLineOrBlank;
                    int end = _textBox.Text.Length;
                    if (end > 1)
                    {
                        _textBox.SelectionStart = end - 1;
                        _textBox.SelectionLength = 0;
                        _textBox.ScrollToCaret();
                    }
                }
                catch (NotSupportedException )
                {
                }
            }
        }
    }
}